<template>
  <div class="container">
    <div class="info row">
      <el-card class="info-left">
        <!-- <div slot="header" class="left-user row fcs">
          <img :src="userInfo.avatar" class="avatar mr20">
          <span class="fz18">{{ userInfo.username }}</span>
        </div> -->
        <div
          v-for="(item, index) in tabList"
          :key="index"
          class="left-item fz14 row"
          :class="tabName === item.name ? 'select' : ''"
          @click="changeTab(item.name)"
        >
          <div class="lh28 tabItem">
            <svg-icon :icon-class="item.icon" />
            <span class="ml40">{{ item.label }}</span>
          </div>
        </div>
      </el-card>
      <el-card class="info-right">
        <div v-show="tabName === 'info'">
          <div class="fz18 mb40 tilBox">
            <svg-icon icon-class="userMsg" />
            <span class="ml40 fwb">账号信息</span>
          </div>
          <div>
            <!-- 内容 -->
            <el-form ref="userInfo" label-position="left" :model="userInfo" :rules="userInfoRules">
              <el-form-item label="所属组织:" required>
                <span v-if="yardName && yardName!='null'">{{ yardName }}</span>
                <span v-if="deptName && deptName!='null'">/{{ deptName }}</span>
                <span v-if="(!yardName || yardName=='null') && (!deptName||deptName=='null')">无</span>
              </el-form-item>
              <el-form-item label="医生签字" size="mini" prop="signImage">

                <!-- <sign v-if="edit" :src="userInfo.signImage" @singnSrc="setSignImage" /> -->
                <div v-if="edit" class="signBox">
                  <sign
                    ref="adjustSign"
                    key="adjustSign"
                    :detail="true"
                    :src="userInfo.signImage"
                    width="200px"
                    height="100px"
                    @singnSrc="setSignImage"
                  />
                  <div class="signButton">
                    <el-link type="primary" :underline="false" @click="patientSign">签字</el-link>
                    <div style="margin-left: 10px;width: 20px;height: 20px;" @click="clickCodeImg(2)">
                      <img class="code" style="width: 20px;height: 20px;" src="@/assets/images/code.jpg" alt="">
                    </div>
                  </div>
                </div>
                <el-image v-else class="signIng" :src="userInfo.signImage" :preview-src-list="signImage" alt="" />
              </el-form-item>
              <el-form-item label="签字密码:" prop="signPasswd">
                <el-input
                  v-model="userInfo.signPasswd"
                  :disabled="!edit"
                  class="w300"
                  clearable
                  type="password"
                  @change="changeSignPasswd"
                />
              </el-form-item>
            </el-form>
            <div class="btns mt30">
              <el-button v-if="!edit" size="mini" type="primary" @click="(edit = true)">编辑</el-button>
              <el-button v-else size="mini" type="primary" @click="submitUser('userInfo')">保存</el-button>
              <el-button v-if="edit" size="mini" @click="edit=false">取消</el-button>
              <el-button size="small" @click="returnUpper">返 回</el-button>
            </div>
          </div>
        </div>
        <div v-show="tabName === 'password'">
          <div class="fz18 mb40 tilBox">
            <svg-icon icon-class="password" />
            <span class="ml40 fwb">修改密码</span>
          </div>
          <div>
            <el-row>
              <el-col :span="12">
                <el-form
                  ref="ruleForm"
                  :model="ruleForm"
                  :rules="rules"
                  label-position="left"
                  label-width="120px"
                  class="ruleForm"
                >
                  <el-form-item label="手机号:" prop="tel ">
                    <el-input
                      ref="tel"
                      v-model="ruleForm.tel"
                      placeholder="请输入手机号"
                      clearable
                      name="tel"
                      disabled
                      type="text"
                      autocomplete="off"
                    />
                  </el-form-item>
                  <el-form-item label="验证码:" prop="messageCode">
                    <el-input
                      ref="messageCode"
                      v-model="ruleForm.messageCode"
                      placeholder="请输入验证码"
                      clearable
                      name="messageCode"
                      type="text"
                      class="w210"
                      autocomplete="off"
                    />
                    <div class="codeText hand" :class="[{'active': btnDisabled}]" @click="getCodeFn">{{ btnDisabled ? captchaTime
                      +
                      '秒后重试' : '获取验证码' }}</div>
                  </el-form-item>
                  <el-form-item label="新密码:" prop="passwd">
                    <el-input v-model="ruleForm.passwd" clearable type="password" />
                  </el-form-item>
                  <el-form-item label="确认密码:" prop="rePasswd">
                    <el-input v-model="ruleForm.rePasswd" clearable type="password" />
                  </el-form-item>
                </el-form>
                <div class="btns mt30">
                  <el-button size="mini" @click="resetForm('ruleForm')">重置</el-button>
                  <el-button size="mini" type="primary" @click="submitForm('ruleForm')">提交</el-button>
                  <el-button size="small" @click="returnUpper">返 回</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>
    </div>
    <el-dialog title="微信扫描" :visible.sync="codeImg" :close-on-click-modal="false" width="300px" @opened="creatQrCode()">
      <div style="display: flex;justify-content: center;">
        <div v-if="codeImg" ref="qrCodeUrl" class="qr-code" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import imgUpload from '@/components/Upload/imgUploadOne';
import { updateImg, setUserSign, getUserSign, getTicket, getTelCode } from '@/api/user';
import { resetUserPasswd } from '@/api/user';
import QRCode from 'qrcodejs2';
import Sign from '@/components/Sign';
import { createWebSocket } from '@/api/socket';
import { getToken } from '@/utils/auth';

export default {
  name: 'Password',
  components: {
    // imgUpload,
    Sign
  },
  data() {
    const tel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
    };
    const messageCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'));
      }
    };
    // const oldPass = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('原密码不能为空'));
    //   }
    // };
    const newPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.ruleForm.rePasswd !== '') {
          this.$refs.ruleForm.validateField('rePasswd');
        }
        callback();
      }
    };
    const rePasswd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.passwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      existUrl: {
        absoluteUrl: '',
        relativeUrl: ''
      },
      tabName: 'info',
      tabList: [
        { name: 'info', label: '账号信息', icon: 'userMsg' },
        { name: 'password', label: '修改密码', icon: 'password' }
      ],
      ruleForm: {
        tel: '',
        messageCode: '',
        userId: '',
        passwd: '',
        rePasswd: ''
      },
      rules: {
        tel: [{ validator: tel, trigger: 'blur' }],
        messageCode: [{ validator: messageCode, trigger: 'blur' }],
        // old_pwd: [{ validator: oldPass, trigger: 'blur' }],
        passwd: [{ validator: newPass, trigger: 'blur' }],
        rePasswd: [{ validator: rePasswd, trigger: 'blur' }]
      },
      userInfo: {
        signImage: 'https://gss0.baidu.com/-fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/9c16fdfaaf51f3de725d465495eef01f3a297917.jpg',
        signPasswd: '',
        reSignPasswd: '',
        userId: ''
      },
      userInfoRules: {
        signImage: [{ required: true, message: '请上传医生签字', trigger: 'change' }],
        signPasswd: [{ required: true, message: '请输入签字密码', trigger: 'blur' }]
      },
      edit: false,

      // 防止验证码按钮重复点击
      btnDisabled: false,
      // 验证码定时器
      interval: null,
      // 验证码倒计时
      captchaTime: 60,
      // 固定时间
      fixedSecond2: 60,
      imgList: [],
      signImage: [],
      codeImg: false,
      code: '',
      ticket: '',
      yardName: '',
      deptName: ''
    };
  },
  computed: {
    // ...mapGetters(['userInfo'])
  },
  mounted() {
    this.imgList.push(this.userInfo.img);
    this.userInfo.userId = getToken('session_id');
    this.ruleForm.userId = getToken('session_id');
    this.ruleForm.tel = getToken('userTel');
    this.yardName = getToken('yardName');
    this.deptName = getToken('deptName');
    this.getTack();
    this.getDetail();
    this.initRandom();
    this.getRecentMonth(-1);

    // this.existUrl.absoluteUrl = this.userInfo.avatar;
  },
  methods: {
    async getTack() {
      const ticket = await getTicket();
      this.ticket = ticket;
    },
    async getDetail() {
      const { data } = await getUserSign({ userId: this.userInfo.userId });
      // console.log(data);
      this.signImage = [data.signImage];
      this.userInfo.signImage = data.signImage;
      this.userInfo.signPasswd = data.signPasswd;
      this.userInfo.reSignPasswd = data.signPasswd;
    },
    changeTab(name) {
      this.tabName = name;
    },
    // 获取手机验证码
    getCodeFn() {
      if (!this.ruleForm.tel) {
        this.$notify.error({
          title: '提示',
          message: '请输入手机号'
        });
        return;
      } else if (!/^1[3-9]\d{9}$/.test(this.ruleForm.tel)) {
        this.$notify.error({
          title: '提示',
          message: '请输入有效手机号'
        });
        return;
      }

      // 防止重复点击
      if (this.btnDisabled) return;
      this.btnDisabled = true;
      this.countdownFun60();
      this.getTelCode();
      // 验证码点击的时间
      sessionStorage.setItem('startTime', new Date().getTime());
    },
    // 手机验证码60秒倒计时
    countdownFun60() {
      this.interval = setInterval(() => {
        this.captchaTime = this.captchaTime - 1;
        if (this.captchaTime === 0) {
          clearInterval(this.interval);
          this.btnDisabled = false;
          this.captchaTime = this.fixedSecond2;
        }
      }, 1000);
    },
    // 获取手机验证码
    async getTelCode() {
      // console.log(sessionStorage.getItem('brand'));
      const res = await getTelCode({
        tel: this.ruleForm.tel,
        ticket: this.ticket
      });
      // console.log(res);
    },
    // 输入签字密码
    changeSignPasswd(e) {
      // console.log(e);
      this.userInfo.reSignPasswd = e;
    },
    // 近N月 - Moment.js
    getRecentMonth: function(n) {
    },
    // 患者签字
    patientSign() {
      this.$refs.adjustSign.HWInitialize();
    },
    initRandom() {
      var random = Math.random().toString(36).substr(2, 10);
      this.random = random;
    },
    // 放大二维码
    clickCodeImg(attribute) {
      this.codeImg = true;
      this.code = this.userInfo.userId + '|signImage' + '|1|' + this.random;
      this.creatQrCode();
      this.init();
    },
    /* 创建二维码 */
    creatQrCode() {
      if (!this.$refs.qrCodeUrl) return;
      new QRCode(this.$refs.qrCodeUrl, {
        text: window.server.SERVER_API[4].routerUrl + '#/esign?code=' + this.code, // 二维码的内容
        // text: '膏珍堂', // 二维码的内容
        width: 150,
        height: 150,
        colorDark: '#000',
        colorLight: '#fff',
        correctLevel: QRCode.CorrectLevel.H
      });
    },
    init() {
      createWebSocket(this.global_callback, this.random);
    },
    // websocket的回调函数，msg表示收到的消息
    global_callback(msg) {
      msg = JSON.parse(msg);
      if (msg.code == this.random) {
        this.userInfo.signImage = msg.path;
        this.codeImg = false;
      }
    },
    // 患者签字
    setSignImage(src) {
      this.userInfo.signImage = src;
      console.log(src);
    },
    submitUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let hintText = '提交更新设置';
          this.hint('create', hintText);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async submitForm(formName) {
      if (!this.ruleForm.tel) {
        return this.$message.info('请输入手机号');
      }
      if (!this.ruleForm.messageCode) {
        return this.$message.info('请输入验证码');
      }
      if (!this.ruleForm.passwd) {
        return this.$message.info('请输入新密码');
      }
      if (!this.ruleForm.rePasswd) {
        return this.$message.info('请确认密码');
      }
      if (this.ruleForm.passwd !== this.ruleForm.rePasswd) {
        return this.$message.info('两次密码输入不一致');
      } else {
        // this.ruleForm.id = this.userInfo.id;
        // changePassword(this.ruleForm).then(({ msg }) => {
        //   this.$message.success(msg);
        //   this.resetForm('ruleForm');
        //   this.logout();
        // });

        // const ticket = await getTicket();
        // this.ticket = ticket;
        this.hint('passwd', '修改密码');
      }
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'create':
              this.submitBrand(row);
              break;
            case 'passwd':
              this.submitPas();
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 医生签字信息
    async submitBrand() {
      const { msg } = await setUserSign({ ...this.userInfo });
      this.$notification('操作成功', 'success', msg);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async logout() {
      await this.$store.dispatch('permission/clearRoute');
      this.$message.success(await this.$store.dispatch('permission/logout'));
      location.reload();
      this.$router.push(`/login`);
    },
    // 上传小程序用户默认logo
    getUrl(url) {
      const { absoluteUrl, relativeUrl } = url;
      this.existUrl.absoluteUrl = absoluteUrl;
      this.existUrl.relativeUrl = relativeUrl;
      if (relativeUrl) {
        this.upDateImg(absoluteUrl, relativeUrl);
      }
    },
    async upDateImg(absoluteUrl, thumb_img) {
      const info = JSON.parse(sessionStorage.getItem('userInfo'));
      const { msg } = await updateImg({ thumb_img });
      this.$notification('操作成功', 'success', msg);
      info.avatar = absoluteUrl;
      sessionStorage.setItem('userInfo', JSON.stringify(info));
      //  this.$router.go(0);
    },
    async submitPas() {
      console.log(this.ruleForm);
      // const info = JSON.parse(sessionStorage.getItem('userInfo'));
      const { msg } = await resetUserPasswd({ ...this.ruleForm, ticket: this.ticket, clientType: 0 });
      this.$notification('操作成功', 'success', msg);
      // this.$notification('操作成功', 'success', msg + '请重新登录');
      // this.$router.push(`/login`);
    },
    // 返回
    returnUpper() {
      this.$router.back();
    }
  }
};

</script>

<style scoped lang="scss">
.container {
  margin: 0 auto;
}
.box {
  width: 100%;
  background: #f4f7f9;
  padding: 15px;
}
.info {
  width: 1200px;
  margin: 0 auto;
  height: 100%;
  .info-left {
    width: 300px;
    height: 100%;
    .left-user {
      // margin-bottom: 50px;
      .avatar {
        width: 50px;
        height: 50px;
        border-radius: 25px;
        display: block;
      }
    }
    .left-item {
      padding: 12px 20px;
      cursor: pointer;
      .tabItem {
        position: relative;
      }
      ::v-deep.svg-icon {
        width: 26px;
        height: 26px;
        position: absolute;
        // top: 0px;
        // left: 0;
      }
      &:hover {
        background: #f6f8fa;
      }
      &.select {
        background: #f6f8fa;
        border-left: 4px solid #8b2e2f;
        padding-left: 16px;
      }
    }
    ::v-deep.el-card__body {
      padding: 0;
    }
  }
  .info-right {
    width: calc(100% - 315px);
    height: 100%;
    .tilBox {
      position: relative;
    }
    ::v-deep.svg-icon {
      position: absolute;
      top: -4px;
      width: 26px;
      height: 26px;
    }
  }
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: block;
}
::v-deep .el-form--label-left .el-form-item__label {
  min-width: 66px;
}
::v-deep .el-input--mini .el-input__inner {
  border: 0;
}
.ruleForm {
  ::v-deep .el-form-item {
    margin-bottom: 50px;
  }
  ::v-deep .el-input--suffix .el-input__inner {
    height: 30px;
  }
}
.el-col-12 {
  padding-left: 20px;
}
.userImg {
  overflow: hidden;
  background-color: #fff;
  border-radius: 50%;
  border: 1px solid #eee;
  ::v-deep .avatar-uploader[data-v-4f5b8920] .el-upload {
    border: 0 !important;
  }
}
::v-deep .el-form-item--mini.el-form-item,
.el-form-item--small.el-form-item {
  display: flex;
}
.ruleForm .el-form-item__content {
  position: relative;
}
.codeText {
  position: absolute;
  right: 0px;
  top: 0px;
  font-size: 12px;
  color: #bf3f3f;
}
.signIng {
  width: 200px;
  height: 100px;
}
.signBox {
  display: flex;
  justify-content: space-around;
  align-items: center;
  .signButton {
    display: flex;
    align-items: center;
  }
}
</style>
